package com.yang.springcloud.service;


import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {

    public String paymentInfo_ok(Integer id){
        return "线程池:   "+Thread.currentThread().getName()+" paymentInfo_ok,id:  "+id+"\t"+"OK";
    }

    @HystrixCommand(fallbackMethod = "paymentInfo_timeoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_timeout(Integer id){
        int timeNumber = 5;
        try { TimeUnit.SECONDS.sleep(timeNumber); }catch (Exception e) {e.printStackTrace();}
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_TimeOut,id：  "+id+"\t"+"呜呜呜"+" 耗时(秒)"+timeNumber;
    }

    public String paymentInfo_timeoutHandler(Integer id){
        return "线程池："+Thread.currentThread().getName()+"   系统繁忙或运行报错，请稍后再试,id：  "+id;
    }

    // ========= 服务熔断 =========
    @HystrixCommand(
            // 兜底的方法
            fallbackMethod = "paymentCircuitBreaker_fallback",
            commandProperties = {
                    // 是否开启断路器
                    @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
                    // 请求次数，表示每 10 次请求失败率达到下面的配置失败率，则熔断
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
                    // 时间范围
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
                    // 失败率达到多少后跳闸，这里表示 60 %
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
            })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if (id < 0){
            // 当传入负数，故意抛出异常
            throw new RuntimeException("*****id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功,流水号："+serialNumber;
    }
    /** 异常的处理方法 */
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能负数，请稍候再试,(┬＿┬)/~~     id: " +id;
    }


}
